package com.ykt.interceptor;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.kit.JsonKit;
import com.ykt.common.config.CommonConfigs;
import com.ykt.common.utils.StringUtil;
import com.ykt.exception.BusinessException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author long.hua
 * @version 1.0.0
 * @since 2015-12-08 23:48
 */
public class AccessInterceptor implements Interceptor {
    private final static Logger LOGGER = LoggerFactory.getLogger(CommonConfigs.API_ACCESS);


    @Override
    public void intercept(Invocation inv) {
        int code = 0;

        long b = System.currentTimeMillis();
        try {
            inv.invoke();
        } catch (Exception e) {
            if (e instanceof BusinessException) {
                code = 0; // 业务异常不算错误
            } else {
                code = -1; // 系统异常才算错误
            }
        }
        long e = System.currentTimeMillis();

        Map<String, Object> msgMap = new LinkedHashMap<>();
        msgMap.put("targetUrl", inv.getActionKey());
        msgMap.put("targetClass", inv.getController().getClass().getName());
        msgMap.put("targetMethod", inv.getMethodName());
        msgMap.put("status", code);
        msgMap.put("costTime", (e - b));

        String msg = JsonKit.toJson(msgMap);
        LOGGER.info(StringUtil.trimAll(msg, '\\'));
    }

}
